import itertools
import subprocess
import shutil
import time
import os
print 'compiling'
p = subprocess.Popen('javac *.java',
    stdout=subprocess.PIPE)
date = time.asctime().replace(':', '_')
os.mkdir(date)
map_count = 100
#open bots.txt
f = open('bots.txt')

#build a list of bots
bots = []
for line in f.readlines():
    if line.strip() not in bots:
        if not line.strip().startswith('#'):
            bots.append(line.strip())

#generate all possible combinations
#matches = itertools.combinations(bots, 2)
matches = []
for bot in bots:
    matches.append((bot, 'java WhatBot'))

combination_dict = {}
beat_dict = {}
lost_to_dict = {}
for bot in bots:
    print bot
    beat_dict[bot] = []
    lost_to_dict[bot] = []
winner = None
loser = None
#run each combination, track results in a dict
for match in matches:
    combination_dict[match] = 0
    for map_number in range(1, map_count+1):
        turn_count = 0
        try:
            os.remove('log.txt')
            time.sleep(.5)
        except (IOError, WindowsError):
            pass
        print '-' * 79
        print 'match: ' + str(match)
        print 'map: ' + str(map_number) + '.txt'

        turnCount = 0
        #os.system('java -jar tools/PlayGame.jar maps/map' + str(map_number) + '.txt 1000 1000 log.txt "' + match[0] + '" "' + match[1] + '"')
        p = subprocess.Popen('java -jar tools/PlayGame.jar maps/map' + str(map_number) + '.txt 1000 200 log.txt "' + match[0] + '" "' + match[1] + '"',
        stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        # stdout=subprocess.PIPE)
        for line in p.stdout.readlines():
            if 'Player 1 Wins!' in line:
                combination_dict[match] += 1
                print match[0] + ' won after ' + str(turn_count) + ' turns!'
                winner = match[0]
                loser = match[1]
            elif 'Player 2 Wins!' in line:
                print match[1] + ' won after ' + str(turn_count) + ' turns!'
                winner = match[1]
                loser = match[0]
            elif 'Turn' in line:
                turn_count = int(line.replace('Turn', '').strip())
            elif 'crash' in line:
                print line
            elif 'timed' in line or 'Timed' in line:
                print line
        time.sleep(.5)
        log = open('log.txt')
        gamestate = []
        for line in log.readlines():

            if 'engine > player2: P' in line:
                turnCount += 1
                gamestate = []
                gamestate.append(line[19:])
            elif line.startswith('P'):
                gamestate.append(line)
        for line in gamestate:
            if line.split()[3] == '1':
                winner = match[1]
                loser = match[0]
            elif line.split()[3] == '2':
                winner = match[0]
                loser = match[1]

        # beat_dict[winner].append(loser)
        # lost_to_dict[loser].append(winner)

        #rename log files and move to a subdir
        shutil.copyfile('log.txt', date + '\\' + winner.replace('java -jar example_bots/', '').replace('java', '').strip() + '_vs_' + loser.replace('java -jar example_bots/', '').replace('java', '').strip() +'_turn_' + str(turnCount) + '_map_' + str(map_number) + '.txt')
print '\n********\n'
        

for match, result in combination_dict.items():
    print '"' + match[0] + '" beat "' + match[1] + '" ' + str(result) + ' times out of ' + str(map_count) + ' matches'
